<?php

namespace App\Http\Controllers\Backend;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\ListenAccess;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function getHistory()
    {
        $data = Input::all();
        if (Input::has('s_time')) $data['s_time'] = urldecode(Input::get('s_time'));
        if (Input::has('e_time')) $data['e_time'] = urldecode(Input::get('e_time'));
        $validate = Validator::make($data, [
            's_time' => 'sometimes|required|date',
            'e_time' => 'sometimes|required|date',
        ]);
        // $validate->passes() messages() failed()
        if ($validate->fails()) {
            $messages = $validate->messages();
            return view('backend.errors.validate', compact('messages'));
        }
        // dd(new Carbon('2015-01-03'));  等同于 Carbon::parse('2015-01-03');
        $e_time = Input::has('e_time') ? Carbon::parse($data['e_time']) : Carbon::now();
        // Carbon::now()->subHours(2);
        // dd(Carbon::parse('15'));  // 无法转换时直接报错, 而不是返回false
        $s_time = Input::has('s_time') ? Carbon::parse($data['s_time']) : Carbon::now()->subMinutes(30);
        $records = ListenAccess::latest()->list()->whereBetween('request_time', [$s_time, $e_time])
            ->paginate(15)->appends(['s_time' => $s_time->toDateTimeString(), 'e_time' => $e_time->toDateTimeString()]);
        return view('backend.users.history', compact('records'));
    }
}
